//
//  FileViewController.m
//  YiLiao
//
//  Created by Infinite on 16/7/1.
//  Copyright © 2016年 Infinite. All rights reserved.
//

#import "FileViewController.h"
#import <AFNetworking.h>
#import <AFHTTPSessionManager.h>
#import "CustomCollectionViewCell.h"

@interface FileViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,NSURLSessionDelegate,NSURLSessionDataDelegate>{
    __strong   NSDictionary * infoDic ;
    __strong   NSArray * allArray;
    UISegmentedControl * segmentedControl;
    
    NSURLSessionDataTask * task;
    NSFileHandle * handle;
    long long totalNum;
    ///下载文件保存的路径
    NSString * _filePath;
    //测试保存button
    CustomCollectionViewCell * cellX;

}

@property (nonatomic,strong) UICollectionView * collectionView;

@end

@implementation FileViewController

//懒加载
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, ScreenHeight) collectionViewLayout:flowLayout];
        
        //定义每个UICollectionView 的大小
        flowLayout.itemSize=CGSizeMake((ScreenWidth-30)/3, (ScreenWidth - 30)/3);
        //定义每个UICollectionView横向距离
        flowLayout.minimumLineSpacing = 5;
        //定义纵向间距
        flowLayout.minimumInteritemSpacing = 5;
        //边距距
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 5, 5);
        
        //注册cell和ReusableView (相当于头部)
        [_collectionView registerNib:[UINib nibWithNibName:@"CustomCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cell"];
        _collectionView.userInteractionEnabled=YES;
        _collectionView.delegate=self;
        _collectionView.dataSource=self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        
        
        
        
        
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor=[UIColor grayColor];
    ///scrollView
    //    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, ScreenHeight)];
    //    scrollView.contentSize=CGSizeMake(self.view.frame.size.width*2, ScreenHeight);
    //    scrollView.userInteractionEnabled=YES;
    //    scrollView.bounces=NO;
    //    scrollView.showsHorizontalScrollIndicator=NO;
    //    scrollView.showsVerticalScrollIndicator=NO;
    //    scrollView.directionalLockEnabled=NO;
    //    scrollView.pagingEnabled=YES;
    //    [self.view addSubview:scrollView];
    ///请求数据
    [self AFNetSession];
    
    ///UISegmentedControl
    NSArray * segmentedData =@[@"公共资源",@"个人资源"];
    segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedData];
    segmentedControl.frame=CGRectMake(10, 20, ScreenWidth-20, 30);
    //默认选中
    segmentedControl.selectedSegmentIndex=0;
    //选中的颜色
    segmentedControl.tintColor = [UIColor blueColor];
    //设置按下和正常状态下的文字颜色
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12],NSFontAttributeName,[UIColor blueColor], NSForegroundColorAttributeName, nil];
    [segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
    
    
    NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    [segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateHighlighted];
    
    //设置分段控件点击相应事件
    [segmentedControl addTarget:self action:@selector(doSomethingInSegment:)forControlEvents:UIControlEventValueChanged];
    
    [self.navigationController.view addSubview:segmentedControl];
    
    ///添加显示collectionView
    [self.view addSubview:self.collectionView];
    
}
-(void)doSomethingInSegment:(UISegmentedControl *)sender{
    NSInteger Index = sender.selectedSegmentIndex;
    switch (Index) {
        case 0:{
            [self AFNetSession];
            
            
        }
            break;
        case 1:{
            [self AFNetSession];
            
        }
            break;
            
        default:
            break;
    }
    
}


#pragma mark - collectionDataSource/delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return allArray.count;;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * fileDic = [allArray objectAtIndex:indexPath.item];
    static NSString * identify = @"cell";
    CustomCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    cell.BGImageView.image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[fileDic objectForKey:@"image_url"]]]];
    cell.TextLabel.text=[fileDic objectForKey:@"name"];
    [cell.Button addTarget:self action:@selector(DownloadButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.Button.tag=indexPath.item;
    cellX=cell;
    return cell;
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"===%zd",indexPath.item);
}
///按钮事件
-(void)DownloadButtonAction:(UIButton *)button{
    if (segmentedControl.selectedSegmentIndex ==0) {
        NSDictionary * pubDic = [allArray objectAtIndex:button.tag];
        [self delock:[pubDic objectForKey:@"url"] :[pubDic objectForKey:@"tname"]];
    }else{
        NSDictionary * perDic = [allArray objectAtIndex:button.tag];
        [self delock:[perDic objectForKey:@"url"] :[perDic objectForKey:@"tname"]];
    }
}
#pragma mark -- 下载
///下载方法 被废弃
//- (void)downloadFileWithOption:(NSDictionary *)paramDic
//                 withInferface:(NSString*)requestURL
//                     savedPath:(NSString*)savedPath
//               downloadSuccess:(void (^)(AFHTTPRequestSerializer*operation, id responseObject))success
//               downloadFailure:(void (^)(AFHTTPRequestSerializer *operation, NSError *error))failure
//                      progress:(void (^)(float progress))progress{
//    
//    AFHTTPRequestSerializer * Serializer = [AFHTTPRequestSerializer serializer];
//    
//    NSMutableURLRequest * request = [Serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
//    NSURL * URL =[NSURL URLWithString:requestURL];
//    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
//    [manager POST:URL parameters:paramDic constructingBodyWithBlock:nil
//         progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//             
//         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//             
//         }];
//}
///下载（可行）
-(void)delock :(NSString*)URLstr :(NSString*)filePathName{
    static int a =0;
    if (cellX.Button.selected==YES) {
        [task cancel];
    }else{
        NSURL * url  =[NSURL URLWithString:URLstr];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
        NSFileManager * manger = [NSFileManager defaultManager];
        NSString * pathFIle = [NSString stringWithFormat:@"Documents/%@",filePathName];
        NSString * file = [NSHomeDirectory() stringByAppendingPathComponent:pathFIle];
        _filePath=file;
        //搬运
        if (![manger fileExistsAtPath:file]) {
            [manger createFileAtPath:file contents:nil attributes:nil];
        }
        
        handle = [NSFileHandle fileHandleForWritingAtPath:file];
        [handle seekToEndOfFile];
        NSDictionary * infoDic = [manger attributesOfItemAtPath:file error:nil];
        [request addValue:[NSString stringWithFormat:@"bytes=%@-",infoDic[NSFileSize]] forHTTPHeaderField:@"Range"];
        NSURLSessionConfiguration * con = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession * session = [NSURLSession sessionWithConfiguration:con delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        [session dataTaskWithRequest:request];
        
        task = [session dataTaskWithRequest:request];
        [task resume];
    }
    
}
//接收到来自服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    //response.expectedContentLength表示接下来文件将要传输的大小
    //响应开始，记录文件的总长度，并进行保存。
    //总长度 = 期望长度 + 本地数据以及下载好的长度
    NSFileManager * manager = [NSFileManager defaultManager];
    NSString * filePath = _filePath;
    NSDictionary * infoDic = [manager attributesOfItemAtPath:filePath error:nil];
    //文件的总长度
    totalNum = response.expectedContentLength+[[infoDic objectForKey:NSFileSize]longLongValue];
    //将总的文件长度保存起来，方便下次应用直接打开时，可以暂时当前文件的下载进度。
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:[NSNumber numberWithLongLong:totalNum] forKey:@"totalNum"];
    
    //需要手动的开启执行操作
    completionHandler(NSURLSessionResponseAllow);
}
//数据的不断写入
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    //不断第进行进度条更新
    //实时进度条的位置 = 之前进度条的位置+当前数据写入的大小*1.0/总量
    
    CustomCollectionViewCell * cell = [[CustomCollectionViewCell alloc]init];
    
    cell.ProgressView.progress=cell.ProgressView.progress+[data length]*1.0 /totalNum;
    [handle writeData:data];
    [self.collectionView reloadData];
    
}
//结束方法，以及错误的输出，二合一的方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
    CustomCollectionViewCell * cell = [[CustomCollectionViewCell alloc]init];
    cell.ProgressView.progress=0;
    
    NSLog(@"===下载完成====%@",_filePath);
    [self.collectionView reloadData];
}
    


#pragma mark - 网络请求获取数据
-(void)AFNetSession{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes=[manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:[NSSet setWithObjects:@"text/html",@"text/plain",nil]];
    NSString * access_Token =[[NSUserDefaults standardUserDefaults]objectForKey:@"access_token"];
    NSLog(@"%@",access_Token);
    
    NSDictionary * parameters =  @{@"access_token":access_Token,@"command":@"ST_F_FL"};
    
    [manager POST:@"http://localhost:8080/st/s" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功:");
        infoDic = responseObject[@"filelist"];
        if (segmentedControl.selectedSegmentIndex ==0) {
            allArray=[infoDic objectForKey:@"per_file"];
        }else{
            allArray=[infoDic objectForKey:@"pub_file"];
        }
        
        [self.collectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
